package java2d.game.sudoku;

import com.formdev.flatlaf.fonts.roboto_mono.FlatRobotoMonoFont;

import javax.swing.*;
import java.awt.*;

/**
 * HintCell是显示宫格数字填写进度（每个Cell表示一个数字）。
 */
public class SudokuHintCell extends JPanel
{
    private static final int WIDTH = 40;
    private static final int HEIGHT = 64;
    private static final Font FONT_DIGIT = new Font(FlatRobotoMonoFont.FAMILY, Font.BOLD, 36);
    private static final Font FONT_HINT = new Font(FlatRobotoMonoFont.FAMILY, Font.PLAIN, 18);
    private static final Constants.Colors COLORS = Constants.DARK;

    private final SudokuBoard board;
    private final int number;

    public SudokuHintCell(SudokuBoard board, int number)
    {
        this.board = board;
        this.number = number;

        Dimension dim = new Dimension(WIDTH, HEIGHT);
        setPreferredSize(dim);
        setMaximumSize(dim);
        setMinimumSize(dim);
    }

    @Override
    protected void paintComponent(Graphics g)
    {
        super.paintComponent(g);

        SudokuModel model = board.getModel();
        int filled = 0;
        for (int r = 0, rn = model.getGridPerColumn(); r < rn; r++)
            for (int c = 0, cn = model.getGridPerRow(); c < cn; c++)
            {
                boolean present = model.hasNumberInGrid(number, r, c);
                if (present)
                    filled += 1;
            }

        if (filled == model.getScale())
            return;

        Graphics2D g2d = (Graphics2D) g.create();

        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

        Color paint = COLORS.board();
        g2d.setPaint(paint);
        g2d.fillRect(0, 0, WIDTH, HEIGHT);

        FontMetrics metrics1 = g.getFontMetrics(FONT_DIGIT);
        FontMetrics metrics2 = g.getFontMetrics(FONT_HINT);
        String digit = String.valueOf(number);
        String hint = String.valueOf(model.getScale() - filled);
        int width1 = metrics1.stringWidth(digit);
        int width2 = metrics2.stringWidth(hint);

        // 居中对齐
        int x1 = (WIDTH - width1) / 2;
        int baseline1 = HEIGHT * 2 / 3 - 6;
        int x2 = (WIDTH - width2) / 2;
        int baseline2 = HEIGHT - 6;

        g2d.setFont(FONT_DIGIT);
        g2d.setPaint(COLORS.anchor());
        g2d.drawString(digit, x1, baseline1);
        g2d.setFont(FONT_HINT);
        g2d.setPaint(COLORS.input());
        g2d.drawString(hint, x2, baseline2);

        g2d.dispose();
    }
}
